#include <Ethernet.h>
#include <SPI.h>
#include <RCSwitch.h>
#include <PubSubClient.h>
RCSwitch mySwitch433 = RCSwitch();
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xE0};
const char *server = "192.168.1.10"; //修改为你的qtt服务器地址
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);
String returnValue = "";
boolean ResponseBegin = false;
void setup()
{
  pinMode(8, OUTPUT);            //7号引脚为正极
  digitalWrite(8, LOW);          //未发送信号时拉低电平防止干扰其他遥控器
  mySwitch433.enableTransmit(9); //输出端口为9
  Serial.begin(9600);
  mqttClient.setServer(server, 1883);       //设置MQTT服务器
  mqttClient.setCallback(subscribeReceive); //设置收到订阅信息后的回调函数
  //初始化网络服务
  if (Ethernet.begin(mac) == 0)
  {
    Serial.println("使用DHCP配置以太网失败");
    if (Ethernet.hardwareStatus() == EthernetNoHardware)
    {
      Serial.println("没有找到以太网硬件。对不起，没有硬件无法运行。");
    }
    if (Ethernet.linkStatus() == LinkOFF)
    {
      Serial.println("以太网电缆未连接。");
    }
    Ethernet.begin(mac);
  }
  else
  {
    Serial.print("网络连接成功，当前IP地址为：");
    Serial.println(Ethernet.localIP());
  }
}
void loop()
{
  delay(2000);
  //服务器连接失败时重建连接
  if (!mqttClient.connected())
  {
    reconnect();
  }
  mqttClient.loop();
}
void reconnect()
{
  while (!mqttClient.connected())
  {
    Serial.print("Attempting MQTT connection...");
    if (mqttClient.connect("myClientID", "username", "password")) //修改为你的mqtt服务器账号密码
    {
      Serial.println("connected");
      mqttClient.publish("Home/RF/433/status", "ClientStandby");
      mqttClient.subscribe("Home/RF/433/send");
    }
    else
    {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}
void subscribeReceive(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Topic: ");
  Serial.println(topic);
  Serial.print("Message: ");
  String returnValue = "";
  for (int i = 0; i < length; i++)
  {
    returnValue += char(payload[i]);
  }
  Serial.println("RF:" + returnValue);
  action(returnValue);
}
void action(String key)
{
  mqttClient.publish("Home/RF/433/status", key.c_str());
  digitalWrite(8, HIGH);
  delay(1000);
  mySwitch433.send(key.toInt(), 24);
  delay(1000);
  digitalWrite(8, LOW);
}
